package com.frame.project.service.system.notice.imp;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.text.Convert;
import com.frame.framework.web.service.imp.AbstractBaseService;
import com.frame.project.domain.system.notice.Notice;
import com.frame.project.repository.system.notice.NoticeRepository;
import com.frame.project.service.system.notice.NoticeService;

/**
 * 
 * @className ：NoticeServiceImpl
 * @describe ：通知公告
 */
@Service
public class NoticeServiceImpl extends AbstractBaseService<Notice> implements NoticeService {

	@Autowired
	private NoticeRepository noticeRepository;
	
	/**
	 * 分页
	 */
	@Override
	public Page<Notice> findByPage(Integer pageNo, Integer pageSize, Notice notice) {
		List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
		Sort sort = Sort.by(orders);
		Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
		
		Page<Notice> page = noticeRepository.findAll((root, query, cb) ->{
			List<Predicate> list = new ArrayList<>();
			list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));
			
			if(StringUtils.isNotBlank(notice.getNoticeTitle())) {
				list.add(cb.and(cb.like(root.get("noticeTitle").as(String.class), notice.getNoticeTitle())));
			}
			
			if(StringUtils.isNotBlank(notice.getNoticeType())) {
				list.add(cb.and(cb.equal(root.get("noticeType").as(String.class), notice.getNoticeType())));
			}
			
			if(StringUtils.isNotBlank(notice.getCreateBy())) {
				list.add(cb.and(cb.like(root.get("createBy").as(String.class), notice.getCreateBy())));
			}
			
			Predicate[] p = new Predicate[list.size()];
			return cb.and(list.toArray(p));
		},pageable);
		
		return page;
	}
	
	@Override
	public void updateNotice(Notice notice) {
		Notice n = findById(notice.getId());
		
		n.setNoticeTitle(notice.getNoticeTitle());
		n.setNoticeType(notice.getNoticeType());
		n.setNoticeContent(notice.getNoticeContent());
		n.setStatus(notice.getStatus());
		
		modify(n);
	}
	
	/**
     * 删除公告对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public void deleteNoticeByIds(String ids)
    {
    	Long[] longArray = Convert.toLongArray(ids);
    	for(Long id : longArray) {
    		remove(id);
    	}
    }
}
